package com.itcoon.cloud.framework.transform.assemble.handler.clazz;

import com.itcoon.cloud.framework.transform.assemble.handler.AssembleHandlerComposite;
import com.itcoon.cloud.framework.transform.constants.ComponentOrderConstants;
import com.itcoon.cloud.framework.transform.definition.InjectDefinition;
import com.itcoon.cloud.framework.utils.SpringUtils;

import java.lang.reflect.Array;
import java.util.List;

public class TargetArrayHandler implements AssembleForTargetClassHandler {

    @Override
    public boolean support(Class<?> targetPropertyType, Object originGetterValue, List<InjectDefinition> injectInfos) {
        return targetPropertyType.isArray() && originGetterValue.getClass().isArray();
    }

    @Override
    public Object handle(Class<?> targetPropertyType, Object originGetterValue, String[] ignoreProperties, List<InjectDefinition> injectInfos) {
        Object[] sourceArray = (Object[]) originGetterValue;
        Class<?> componentType = targetPropertyType.getComponentType();
        Object targetArray = Array.newInstance(componentType, sourceArray.length);
        AssembleHandlerComposite composite = SpringUtils.getBean(AssembleHandlerComposite.class);
        for (int i = 0; i < sourceArray.length; i++) {
            Object sourceValue = sourceArray[i];
            Array.set(targetArray, i, sourceValue == null ? null : composite.handle(componentType, sourceValue, ignoreProperties, injectInfos));
        }
        return targetArray;
    }

    @Override
    public int getOrder() {
        return ComponentOrderConstants.ASSEMBLE_HANDLER_MIN;
    }
}
